﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Slja.BLL;
using FrameWork.Components;
using System.Collections;
using Slja.Model;
using Slja.BLL.Platform;
using System.Text.RegularExpressions;
using Slja.Model.Platform;
using Slja.Utility;
namespace FrameWork.web.Web.Project
{
    public partial class PrjWizard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Wizard1.ActiveStepChanged += new EventHandler(Wizard1_ActiveStepChanged);
            Wizard1.SideBarButtonClick += new WizardNavigationEventHandler(Wizard1_SideBarButtonClick);
            Wizard1.FinishButtonClick += new WizardNavigationEventHandler(Wizard1_FinishButtonClick);
            btnBack.Click += new EventHandler(btnBack_Click);
            //btnPreview.Click += new EventHandler(btnPreview_Click);
            btnPreview.Attributes["onclick"] = "PreviewOrder();";
            btnList.Click += new EventHandler(btnList_Click);
            if (!IsPostBack)
            {
                BindDropdownlist();
                BindRegion();
                BindSaleType();
                
            }
        }

        void btnPreview_Click(object sender, EventArgs e)
        {
            ////window.showModalDialog("SelPage/MailBuilder.aspx?orderid=" + orderid + "&rdm=" + Math.random(), "", sFeatures);
            //string script = string.Format("window.showModalDialog('/web/project/PrintPage/OrderDetailPrint.aspx?orderid={0}'+Math.random(),window,'');", hdfPrjID.Value);
            //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Preview", script, true);
        }

        void btnList_Click(object sender, EventArgs e)
        {
            Response.Redirect("OrderListFrame.aspx?ViewType=PRIVATE");
        }

        void btnBack_Click(object sender, EventArgs e)
        {
            plhImgbutton.Visible = false;
            Wizard1.Visible = true;
            plhPreviewOrder.Visible = false;
        }
        //订单添加、或修改
        void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (!CheckInput()) { return; }

            OrderBLL bll = new OrderBLL();
            OrderModel model = new OrderModel();
            string tip = "订单添加成功！";
            if (hdfPrjID.Value.Trim() == "")
            {
                int ShopId = EnsureShopID();
               
                AssignModel(model);
                string OriPrjid = tbxPrjID.Text.Trim();
                string NewPrjid = WebCommon.NewPrjID(DateTime.Today, drpProductType.SelectedValue);
                if (OriPrjid != NewPrjid)
                {
                    WebCommon.AlertMsg(Page, string.Format("订单ID号{0}被占用，系统自动按新的ID:{1}生成订单", OriPrjid,NewPrjid));
                }                
                model.PrjID = NewPrjid;
                OrderLogModel log = new OrderLogModel();
                {
                    log.CurState = (int)SaleState.None;
                    log.Dtm = DateTime.Now;
                    log.NextState = (int)SaleState.NewOrder;
                    log.NextUser = model.ManagerUser;
                    log.Note = "客户代表提交";
                    log.OpType = (int)Btn.Submit;
                    //log.OrderID = OrderModel.ID;
                    log.UserID = Common.Get_UserID;
                    log.UserName = UserData.GetUserData.U_CName;
                }
                model.ID = bll.AddOrderWithLog(model, log);//新增订单
               
                tbxPrjID.Text = model.PrjID;//赋值项目编号
                hdfPrjID.Value = model.ID.ToString();//赋值项目ID         
            }
            else
            {
                AssignModel(model);
                model.ID = int.Parse(hdfPrjID.Value);
                model.PrjID = tbxPrjID.Text.Trim();
                bll.Update(model);
                tip = "订单修改成功！";
            }
            plhImgbutton.Visible = false;
            Wizard1.Visible = false;
            plhPreviewOrder.Visible = true;
            lbSuccessful.Text = tip;

        }
        bool CheckInput()
        {
            if (hdfClientID.Value == "")
            {
                WebCommon.AlertMsg(Page, "请选择客户！");
                return false;
            }
            if (hdfCityID.Value == "")
            {
                WebCommon.AlertMsg(Page, "城市无法识别，请重新选择！");
                return false;
            }
            if (drpSaleType.SelectedValue == "1" && hdfAgentCorp.Value == "")
            {
                WebCommon.AlertMsg(Page, "请选择代理商未！");
                return false;
            }
            if (hdfPrjManager.Value == "")
            {
                WebCommon.AlertMsg(Page, "项目管理人需要确认！");
                return false;
            }
            if (tbxShopName.Text == "")
            {
                WebCommon.AlertMsg(Page, "请确定店名！");
                return false;
            }
            return true;
        }
        private void AssignModel(OrderModel model)
        { 
            if (hdfAgentCorp.Value != "")
            {
                model.AgentClientID = int.Parse(BLLCommon.ObjIDFromSpliting(hdfAgentCorp.Value));
            }
            model.AgentSaleMan = tbxAgentSalesman.Text.Trim();
            model.City = int.Parse(BLLCommon.ObjIDFromSpliting(hdfCityID.Value));
            if (hdfClientID.Value != "")
            {
                model.ClientID = int.Parse(BLLCommon.ObjIDFromSpliting(hdfClientID.Value));
            }
            model.CreateTime = DateTime.Now;
            model.Creator = Common.Get_UserID;// BusinessFacade.sys_UserDisp(
            if (hdfPrjManager.Value != "")
            {
                model.ManagerUser = int.Parse(BLLCommon.ObjIDFromSpliting(hdfPrjManager.Value));
                model.CurOpUserName = BLLCommon.ObjNameFromSpliting(hdfPrjManager.Value);
            }
            model.PlanEndDate = DateTime.Parse(tbxPrjstart.Text.Trim());
            if (hdfPlanner.Value != "")
            {
                model.PlanMaker = int.Parse(BLLCommon.ObjIDFromSpliting(hdfPlanner.Value));
            }
            model.PlanStartDate = DateTime.Parse(tbxPrjend.Text.Trim());
            //model.PrjID = WebCommon.NewPrjID(DateTime.Today, drpProductType.SelectedValue);
            model.PrjName = tbxPrjName.Text.Trim();
            model.ProductType = drpProductType.SelectedValue;
            model.Region = drpRegion.SelectedItem.Text;
            if (hdfSalesman.Value != "")
            {
                model.SaleMan = int.Parse(BLLCommon.ObjIDFromSpliting(hdfSalesman.Value));
            }
            model.SaleType = int.Parse(drpSaleType.SelectedValue);
            if (hdfShopName.Value != "")
            {
                EnsureShopID();//确保商店存入
                model.ShopID = int.Parse(BLLCommon.ObjIDFromSpliting(hdfShopName.Value));
            }
            model.Enum_SaleState = SaleState.NewOrder;
           
        }
        private int EnsureShopID()
        {
            //用户填写了新的商店
            int shopid = 0;
            if (hdfShopName.Value.IndexOf(tbxShopName.Text.Trim()) == -1)
            {
                string strCityID =  BLLCommon.ObjIDFromSpliting(hdfCityID.Value);
                int cityId ;
                if(!int.TryParse(strCityID,out cityId))
                {
                   //
                    return 0;
                }
                ShopBLL bll = new ShopBLL();
                ShopModel model = new ShopModel();                
                model.Address = tbxAddress.Text.Trim();
                model.City = cityId;
                model.InnerCode = "0";
                model.SaleVolume = tbxSaleVolume.Text.Trim();
                //model.ShopID;
                model.ShopLev = tbxShopLev.Text.Trim();
                model.ShopLinkman = tbxShopLinkman.Text.Trim();
                model.ShopLinkmanTel = tbxShopLinkmanTel.Text.Trim();
                model.ShopName = tbxShopName.Text.Trim();
                model.ShopPromotor = tbxShopPromotor.Text.Trim();
                model.Square = tbxShopSquare.Text.Trim();
                model.TLCode = tbxShopTLCode.Text.Trim();
               
                shopid = bll.Add(model);
                hdfShopName.Value = string.Format("{0}*{1}", shopid, model.ShopName);//给hidden赋值

            }
            return shopid;
        }

        void Wizard1_SideBarButtonClick(object sender, WizardNavigationEventArgs e)
        {
            hdfCurStepIdx.Value = e.CurrentStepIndex.ToString();
        }

        void Wizard1_ActiveStepChanged(object sender, EventArgs e)
        {
            hdfCurStepIdx.Value = Wizard1.ActiveStepIndex.ToString();
            if (Wizard1.ActiveStepIndex == 2)
            {
                if (hdfCityID.Value != "")
                {
                    //项目经理
                    string CityId = BLLCommon.ObjIDFromSpliting(hdfCityID.Value);
                    UserBLL bll = new UserBLL();
                    UserModel PrjManger = bll.GetManagerFromCity(CityId);
                    if (PrjManger == null)
                    {
                        PrjManger = WebCommon.GetDefaultOrderManager();
                    }                    
                    tbxPrjManager.Text = PrjManger.U_CName;
                    hdfPrjManager.Value = string.Format("{0}*{1}",PrjManger.UserID, PrjManger.U_CName);
                    //项目名称
                    string strProductTypeCN = Regex.Match(drpProductType.SelectedItem.Text,@"^[^\(\)]+").Value;
                    string strPrjname = tbxCity.Text + tbxShopName.Text + strProductTypeCN;
                    tbxPrjName.Text = strPrjname;
                    tbxPrjID.Text = WebCommon.NewPrjID(DateTime.Today, drpProductType.SelectedValue);
                }
            }
        }
        
        protected void img_Click(object sender, EventArgs e)
        {
            plhImgbutton.Visible = false;
            ImageButton imb = (ImageButton)sender;
            if (imb.ID == "imgPrjNew")
            {
                Wizard1.Visible = true;
            }
            else if (imb.ID == "imgPrjList")
            {
                Response.Redirect("OrderListFrame.aspx?ViewType=private");
            }
        }
        protected void BindDropdownlist()
        {           
            ArrayList lst =WebCommon.GetProductTypeArraylist();
            for (int i = 0; i < lst.Count; i++)
            {
                sys_FieldValueTable fv = (sys_FieldValueTable)lst[i];
                drpProductType.Items.Add(new ListItem(fv.V_Text,fv.V_Code));
            }
           
        } 
        protected void BindRegion()
        {
            QueryParam qp = new QueryParam();
            qp.Where = string.Format("Where V_F_Key='{0}'", "Region");
            qp.Orderfld = " V_ShowOrder ";
            qp.OrderType = 0;
            ArrayList lst = new ArrayList();
            int cout;
            lst = BusinessFacade.sys_FieldValueList(qp, out cout);
            
            for (int i = 0; i < lst.Count; i++)
            {
                sys_FieldValueTable fv = (sys_FieldValueTable)lst[i];
                drpRegion.Items.Add(new ListItem(fv.V_Text,fv.V_Code));
            }          
        }
        protected void BindSaleType()
        {
            List<EnumUtility<SaleType>.EnumInfo> list = EnumUtility<SaleType>.GetEnumList();
            for (int i = 0; i < list.Count; i++)
            {
                EnumUtility<SaleType>.EnumInfo info = list[i];
                ListItem it = new ListItem(info.Descr, info.Value.ToString());
                if(info.Item == SaleType.AgentCorpSale)
                {
                    it.Selected = true;
                }
                drpSaleType.Items.Add(it);
            }           
        }
    }
}